﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PetaPoco;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin
{
    [Area("Admin")]
    [Authorize]
    public class UserController : Base
    {
        private readonly AdminUserService _adminUserService;
        private readonly AdminUserGroupService _adminUserGroupService;
        private readonly LogService _logService;
        public UserController(AdminUserService adminUserService, AdminUserGroupService adminUserGroupService, LogService logService)
        {
            _adminUserService = adminUserService;
            _adminUserGroupService = adminUserGroupService;
            _logService = logService;
        }

        public async Task<IActionResult> IndexAsync(int page = 1, int limit = 15, int json = 0)
        {
            if (json == 1)
            {
                Page<ViewAdminUser> list = await _adminUserService.GetPageListAsync(page, limit);
                return Json(new { code = 0, data = list.Items, count = list.TotalItems });
            }
            return View();
        }

        public async Task<IActionResult> AddOrEditAsync(int? id, int edit = 0)
        {
            if (edit == 1)
            {
                EditAdminUser data = await _adminUserService.GetEditAsync(id);
                return Json(new { status = 1, data });
            }
            List<AdminUserGroup> adminUserGroup = await _adminUserGroupService.GetListAsync();
            ViewBag.adminUserGroup = adminUserGroup;
            ViewBag.id = id;
            return View();
        }

        [XssFieldFilter]//防Xss
        public async Task<IActionResult> PassWordAsync(int json = 0, int edit = 0, EditPassWord editPass = null)
        {
            ViewAdminUser adminUser = await UserClaims();
            int uid = adminUser.Id;

            if (json == 1)
            {
                EditAdminUser data = await _adminUserService.GetEditAsync(uid);
                return Json(new { status = 1, data });
            }
            else if (edit == 1)
            {
                if (ModelState.IsValid)
                {
                    string oldPassWord = MD5Utility.MD5Encrypt32(editPass.OldPassword).ToLower();
                    AdminUser user = await _adminUserService.GetAsync(uid);
                    if (user.Password != oldPassWord)
                        return Json(new { status = 0, msg = "旧密码不正确！" });

                    //string pattern = @"^[0-9a-zA-Z_ !""#$%&'()*+,-./:;<=>?@\[\]\^_`{|}~]{6,20}$";
                    //Regex regex = new(pattern);
                    //if (!regex.IsMatch(editPass.Password))
                    //    return Json(new { status = 0, msg = "新密码为字母数字下划线及特殊字符组合,且最少6位最多20位！" });

                    editPass.Password = MD5Utility.MD5Encrypt32(editPass.Password).ToLower();

                    await _adminUserService.PassWordUpdateAsync(editPass, uid);
                    await _logService.InsertLogSqlAsync(await UserInfoAsync(), "修改用户 Id: " + uid + " 密码");
                    return Json(new { status = 1, msg = "修改成功！" });
                }
                else
                {
                    var error = ModelState.GetErrorMessages();
                    return Json(new { status = 0, msg = error });
                }

            }
            else
            {
                ViewBag.id = uid;
                return View();
            }
        }

        [HttpPost, ActionName("CreatePost")]
        [XssFieldFilter]//防Xss
        public async Task<IActionResult> CreatePostAsync(EditAdminUser user)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(user.Password))
                    return Json(new { status = 0, msg = "新增用户密码不能为空！" });

                if (await _adminUserService.GetByUsernameAsync(user.Username) == false)
                    return Json(new { status = 0, msg = "该用户名已存在，请重新输入！" });

                AdminUser adminUser = new()
                {
                    Gid = user.Gid,
                    Username = user.Username,
                    Password = MD5Utility.MD5Encrypt32(user.Password).ToLower(),
                    Nickname = user.Nickname,
                    Status = user.Status
                };
                await _adminUserService.InsertAsync(adminUser);
                await _logService.InsertLogSqlAsync(await UserInfoAsync(), "添加用户");
                return Json(new { status = 1, msg = "添加成功！" });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        [HttpPost, ActionName("EditPost")]
        [XssFieldFilter]//防Xss
        public async Task<IActionResult> EditPost(EditAdminUser user, int id)
        {
            if (ModelState.IsValid)
            {
                AdminUser post = await _adminUserService.GetAsync(id);
                if (post == null)
                    return Json(new { status = 0, msg = "请勿非法提交！" });

                if (user.Username != post.Username)
                    if (await _adminUserService.GetByUsernameAsync(user.Username) == false)
                        return Json(new { status = 0, msg = "该用户名已存在，请重新输入！" });


                if (!string.IsNullOrEmpty(user.Password))
                    user.Password = MD5Utility.MD5Encrypt32(user.Password).ToLower();

                await _adminUserService.UpdateAsync(user, id);
                await _logService.InsertLogSqlAsync(await UserInfoAsync(), "编辑用户 id:" + id);
                return Json(new { status = 1, msg = "修改成功！" });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            if (await _adminUserService.DeleteByPriKeyAsync(id) > 0)
            {
                await _logService.InsertLogSqlAsync(await UserInfoAsync(), "删除用户 id:" + id);
                return Json(new { status = 1, msg = "删除成功！" });
            }

            else
                return Json(new { status = 0, msg = "删除失败！" });
        }

    }
}
